package com.ahwei.controller;

import com.ahwei.context.AppContext;
import com.ahwei.pojo.User;
import com.ahwei.pojo.UserDetail;
import com.ahwei.pojo.Video;
import com.ahwei.pojo.VideoDetail;
import com.ahwei.pojo.enums.Result;
import com.ahwei.pojo.model.PageResult;
import com.ahwei.service.VideoService;
import com.ahwei.service.impl.UserServiceImpl;
import com.ahwei.service.impl.VideoServiceImpl;
import com.ahwei.util.DateUtils;
import com.ahwei.util.FileUtils;
import com.ahwei.util.LogUtils;
import com.ahwei.util.StringUtils;
import com.ahwei.util.anno.Controller;
import com.ahwei.util.anno.FunctionMapping;
import com.ahwei.util.anno.RequestMapping;
import com.ahwei.web.filter.AntiStealingLinkFilter;
import org.apache.commons.collections4.MapUtils;
import org.springframework.util.Assert;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author：ahwei163@qq.com
 * @date: 202*-03-15 15:37:49
 * @description: 这是一个Java文件！
 */
@Controller
@MultipartConfig
public class VideoController {

    @FunctionMapping("获取视频类型列表")
    @RequestMapping("/getVideoTypeList")
    public List<Map<String, Object>> getVideoTypeList() {
        return videoService().getVideoTypeList();
    }

    @FunctionMapping("新增视频类型")
    @RequestMapping("/addVideoType")
    public Boolean addVideoType(String typeName) {
        return videoService().addVideoType(typeName);
    }

    @FunctionMapping("编辑视频类型")
    @RequestMapping("/editVideoType")
    public Boolean editVideoType(String typeName, String typeId) {
        return videoService().editVideoType(typeName, typeId);
    }

    @FunctionMapping("下载视频")
    @RequestMapping("/downloadVideo")
    public String downloadVideo(long uid, long vid, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        //获取视频文件名
        String fileName = videoService().findByVid(vid, uid).getVideoUrl();
        //判断用户类型
        int roleId = new UserServiceImpl().findUserByUid(uid).getRoleId();
        if (roleId == AppContext.ROLE_STUDENT) {
            return "msg:" + "<script>alert('下载视频请开通vip！');window.location.href='html/openVIP.html';</script>";
        } else {
            //不是普通学生，有权限下载
            Video video = videoService().findByVid(vid, uid);
            if (video != null) {
                VideoDetail videoDetail = video.getVideoDetail();
                //视频下载量加一
                videoDetail.setDownloadCount(videoDetail.getDownloadCount() + 1);
                videoService().updateVideoDetail(videoDetail);
            }
            FileUtils.fileDownload(request, response, fileName);
        }
        return "msg:downloadVideo..." + fileName;
    }

    @FunctionMapping("上传视频")
    @RequestMapping("/uploadVideo")
    public String uploadVideo(HttpServletRequest request, HttpSession session) {
        try {
            User user = (User) session.getAttribute("currentUser");
            Map<String, String> map = FileUtils.fileUpload(request);
            //获取需要的数据
            String videoName = map.get("videoName");
            String videoUrl = map.get("videoUrl");
            String coverUrl = map.get("coverUrl");
            Integer type = MapUtils.getInteger(map, "type");

            Integer status = MapUtils.getInteger(map, "status");

            String videoDetailStr = map.get("videoDetail");
            String issuer = user.getAccount();
            String keyword = map.get("keyword");

            Assert.hasLength(videoName, "请填写视频名称");
            Assert.hasLength(videoUrl, "请上传视频");
            Assert.hasLength(coverUrl, "请上传封面");
            Assert.notNull(type, "请选择类型");
            Assert.notNull(status, "请选择状态");
            Assert.hasLength(videoDetailStr, "请填写视频简介");
            Assert.hasLength(keyword, "请填写关键字");

            //添加视频和视频详情
            VideoDetail videoDetail = new VideoDetail(0L, videoDetailStr, new Date(), issuer, 0, keyword, 0, 0, 0);
            Video video = new Video(0L, videoName, videoUrl, coverUrl, type, status, videoDetail);

            Result result = videoService().addVideo(video);
            return "msg:" + "<script>alert('" + result.getMsg() + "');window.location.href='html/videoUpload.html';</script>";
        } catch (Exception e) {
            e.printStackTrace();
            return "exception:" + "<script>alert('" + e.getMessage() + "');window.location.href='html/videoUpload.html';</script>";
        }
    }

    @FunctionMapping("多条件搜索视频")
    @RequestMapping("/searchVideo")
    public PageResult<Video> searchVideo(String keyword, String sort, String column, Integer pageNo, String status) {
        return videoService().findAll(keyword, sort, column, pageNo, null, status);
    }

    @FunctionMapping("根据类型获取视频")
    @RequestMapping("/getVideoByType")
    public List<Video> getVideoByType(long type) {
        return videoService().findByType(type);
    }

    @FunctionMapping("获取前十视频")
    @RequestMapping("/getVideoByTop")
    public List<Video> getVideoByTop(String column) {
        return videoService().findColumnOrderBy(column);
    }

    @FunctionMapping("获取视频列表")
    @RequestMapping("/getVideoList")
    public List<Video> getVideoList() {
        List<Video> videoList = new ArrayList<>();
        //获取全部视频
        List<Video> videoLists = videoService().findAll(null, null, null, null, null, null).getData();
        //遍历类型集合，给每个类型装最多4个视频
        List<Map<String, Object>> videoTypeList = videoService().getVideoTypeList();

        Set<Object> videoTypeIds = videoTypeList.stream().map(videoType -> {
            return videoType.get("typeId");
        }).collect(Collectors.toSet());
        for (Object videoType : videoTypeIds) {
            int count = 0;
            for (Video video : videoLists) {
                //判断类型是否一致 并且过滤下架视频
                if (String.valueOf(videoType).equals(String.valueOf(video.getType()))
                        && video.getStatus() != 0) {
                    videoList.add(video);
                    count += 1;
                    //数量超过4停止循环
                    if (count >= AppContext.INDEX_COUNT) {
                        break;
                    }
                }
            }
        }
        return videoList;
    }

    @FunctionMapping("视频管理")
    @RequestMapping("/getVideoListManager")
    public PageResult<Video> getVideoListManager(String keyword, Integer pageNo, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        String account = null;
        // 如果不是管理员只能管理自己的视频
        if (user.getRoleId() != 0) {
            account = user.getAccount();
        }
        return videoService().findAll(keyword, null, null, pageNo, account, null);
    }

    @FunctionMapping("修改视频")
    @RequestMapping("/updateVideo")
    public String updateVideo(long vid, Integer status) {
        int i = videoService().updateVideo(new Video(vid, null, null, null, null, status, null));
        return i > 0 ? "ajax:true" : "ajax:false";
    }

    @FunctionMapping("修改视频信息")
    @RequestMapping("/videoInfoUpdate")
    public String videoInfoUpdate(long vid, String editType, String newText, HttpServletRequest request, HttpSession session) {
        Video video = new Video();
        switch (editType) {
            case "videoName":
                video.setVideoName(newText);
                break;
            default:
                throw new RuntimeException("非法请求！！!");
        }
        //执行修改
        video.setVid(vid);
        videoService().updateVideo(video);

        String referer = request.getHeader("referer").replace(AntiStealingLinkFilter.url, "");

        return "redirect:" + referer;
    }

    @FunctionMapping("获取一个视频")
    @RequestMapping("/getVideo")
    public Video getVideo(HttpSession session, HttpServletResponse response) throws IOException {
        long vid = (long) session.getAttribute("vid");
        User user = (User) session.getAttribute("currentUser");
        return videoService().findByVid(vid, user.getUid());
    }

    private VideoService videoService() {
        return new VideoServiceImpl();
    }
}
